package com.lc.common.component;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign拦截器，将token原请求的头中，放入请求头。如果不存在，则跳过
 *
 * @author LingChou
 */
@Configuration
public class FeignInterceptor implements RequestInterceptor {

    @Value("${spring.application.name:unKnow}")
    private String localServerName;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            requestTemplate.header("S_A", localServerName);
            return;
        }
        //业务系统鉴权token
        HttpServletRequest request = requestAttributes.getRequest();
        String loginInfoHeader = request.getHeader("login-info");
        if (loginInfoHeader != null) {
            requestTemplate.header("login-info", loginInfoHeader);
        }
        //服务内系统鉴权token
        String serverAuthenticationHeader = request.getHeader("S_A");
        requestTemplate.header("S_A",
                serverAuthenticationHeader == null ? localServerName : serverAuthenticationHeader);
    }
}